<!--
 * @Description: Description
 * @Author: wning
 * @Date: 2023-03-25 09:38:00
 * @LastEditors: wning
 * @LastEditTime: 2023-03-31 11:08:41
-->

<template>
  <x-sub-page class="rectify-inform-add" :content="title" @goBack="handleBack">
    <el-form :model="params" :rules="rules" ref="params" class="statement-inline" label-position="top">
      <div class="statement-components">
        <div class="panl-title">
          <span>基础信息</span>
        </div>

        <el-row :gutter="20">
          <x-col :span="8">
            <el-form-item :label="$t('financialSynergy.statement.supplier')" prop="supplierId">
              <template #label>
                <em class="required-icon"> * </em>
                <span>{{ $t('financialSynergy.invoice.supplier') }}</span>
              </template>
              <supplier-select
                ref="supplier-select"
                :value="params.supplierName"
                :placeholder="'请选择供应商'"
                @on-change="handleChangeSupplier"
              >
              </supplier-select>
            </el-form-item>
          </x-col>
          <x-col :span="8">
            <el-form-item :label="$t('financialSynergy.statement.accountBeginDate')" prop="beginDate">
              <el-date-picker
                v-model="params.beginDate"
                type="date"
                value-format="yyyy-MM-dd"
                :placeholder="'请输入'"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
            </el-form-item>
          </x-col>
          <x-col :span="8">
            <el-form-item :label="$t('financialSynergy.statement.accountEndDate')" prop="endDate">
              <el-date-picker
                v-model="params.endDate"
                type="date"
                value-format="yyyy-MM-dd"
                :placeholder="'请输入'"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
            </el-form-item>
          </x-col>
          <x-col :span="8">
            <el-form-item :label="$t('financialSynergy.statement.totalPriceInfo')" prop="totalAmount">
              <el-input
                v-model="params.totalAmount"
                :placeholder="$t('financialSynergy.statement.autoCount')"
                style="width: 100%"
                disabled
                maxlength="20"
              ></el-input>
            </el-form-item>
          </x-col>
          <x-col :span="8">
            <el-form-item :label="$t('financialSynergy.statement.untaxedAmountInfo')" prop="untaxedAmount">
              <el-input
                v-model="params.untaxedAmount"
                :placeholder="$t('financialSynergy.statement.autoCount')"
                style="width: 100%"
                disabled
                maxlength="20"
              ></el-input>
            </el-form-item>
          </x-col>
          <x-col :span="8">
            <el-form-item :label="$t('financialSynergy.statement.totalAccount')" prop="totalAccount">
              <el-input
                v-model="params.totalAccount"
                :placeholder="$t('financialSynergy.statement.autoCount')"
                style="width: 100%"
                disabled
                maxlength="20"
              ></el-input>
            </el-form-item>
          </x-col>
          <x-col :span="24">
            <el-form-item :label="$t('financialSynergy.statement.remark')">
              <el-input
                placeholder="请输入"
                v-model="params.remark"
                type="textarea"
                style="width: 100%"
                maxlength="200"
                show-word-limit
                rows="4"
                clearable
              />
            </el-form-item>
          </x-col>
        </el-row>
      </div>

      <div class="statement-components">
        <div class="panl-title">
          <span>对账单明细</span>
        </div>
      </div>
      <el-row type="flex" class="tools" justify="space-between">
        <el-col :span="20" class="btnStyle">
          <el-button type="primary" @click="handlePurchase"  > {{ '来源收货单' }}</el-button>
          <el-button @click="handleBatchDel" type="danger"> {{ $t('common.batchDelete') }}</el-button>
        </el-col>
      </el-row>
      <x-table
        ref="tableCom"
        :isPagination="false"
        :data-source="params.billDetailList"
        :row-key="'id'"
        @on-selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          v-for="(item, index) in columns"
          :key="index"
          :prop="item.prop"
          :fixed="item.fixed"
          :show-overflow-tooltip="true"
          :width="item.width"
          :min-width="item.minWidth || '-'"
          :label="item.label"
          :sortable="'custom'"
        >
          <template #default="scope">
            <span v-if="item.prop === 'state'">{{
              selectDictLabel(dictOptions['srm_bill.state'], scope.row[item.prop])
            }}</span>
            <span v-else-if="item.prop === 'materialUnit'">{{selectDictLabel(dictOptions['srm_material.material_unit'], scope.row[item.prop])}}</span>
            <span v-else>{{ scope.row[item.prop] | emptyVal }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <el-link type="danger" :underline="false" @click="delRow(scope.row.id)">删除</el-link>
          </template>
        </el-table-column>
      </x-table>
    </el-form>

    <fixed-btn-area v-if="isDetail">
      <el-button @click="handleBack"> {{ $t('common.cancel') }} </el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading"> {{ '提交' }} </el-button>
    </fixed-btn-area>
    <purchase-order-dialog
      ref="purchaseOrderDialog"
      :multiple="true"
      :supplierId="params.supplierId"
      @on-confirm="confirmSubmit"
    ></purchase-order-dialog>
  </x-sub-page>
</template>
<script>
  import { formatSubmitFiles, QueryDictMixin, throttle,selectDictLabel } from '@package/utils'
  import SupplierSelect from '@/components/supplier-select/index.vue'
  import { detailColumns } from '@/modules/financialSynergy/config/statementAccount.js'
  import { apiBillAdd, apiBillUpdate, apiGetBillDetail } from '@/modules/financialSynergy/api/statementAccount.js'
  import { EnumApiCode } from '../../../../../../globalEnum.js'
  import PurchaseOrderDialog from './PurchaseOrderDialog.vue'
  //   import { mapState, mapActions } from 'pinia'
  //   import { pinias } from '@/common/pinia'
  //   const { login } = pinias
  export default {
    name: 'StatementAccountAdd',
    components: { PurchaseOrderDialog, SupplierSelect },
    mixins: [QueryDictMixin],
    inject: ['closePages'],
    data() {
      return {
        columns: detailColumns,
        id: '',
        params: {
          beginDate: '',
          endDate: '',
          supplierId: '',
          supplierName: '',
          remark: '',
          billDetailList: []
        },
        isDetail: true,
        selectData: [],
        rules: {
          supplierName: [{ required: true, message: '请选择供应商', trigger: 'blur' }],
          endDate: [{ required: true, message: '请选择对账结束日期', trigger: 'blur' }],
          beginDate: [{ required: true, message: '请选择对账开始日期', trigger: 'blur' }]
        },
        loading: false,
        srmDictKeys: ['srm_bill.state','srm_material.material_unit'],
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 86_400_000
          }
        }
      }
    },
    computed: {
      //   ...mapState(login, ['supplierId']),
      title() {
        return `${this.id ? '编辑' : '新建'}`
      }
    },
    created() {
      this.id = this.$route.query.id
      this.initDictConfig()
      this.id && this.init()
    },
    methods: {
     selectDictLabel,
      async init() {
        const { data, code } = await apiGetBillDetail(this.id)
        if (code === EnumApiCode.Success) {
          this.params = { ...data }
          this.params.billDetailList?.forEach((item) => {
            item.deliveryQuantityLast = item.deliveryQuantity
          })
          this.params.totalAccount = data.totalQuantity
        }
      },
      // 多行选中
      handleSelectionChange(rows) {
        this.selectData = rows
      },
      handleChangeSupplier(val) {
        if (val.id != this.params.supplierId) {
          this.params.supplierId = val.id
          this.params.supplierName = val.fullName

          this.params.billDetailList = []
          this.params.totalAmount = ''
          this.params.untaxedAmount = ''
          this.params.totalAccount = ''
        }
      },
      // 批量删除
      handleBatchDel() {
        if (this.selectData.length === 0) {
          this.$message.error('请至少选择一条数据')
          return
        }
        this.delRow()
      },
      //    删除
      delRow(i) {
        const rowIndexs = i
          ? [i]
          : this.selectData.map((el) => {
              return el.id
            })
        this.$confirm('是否删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.params.billDetailList = this.params.billDetailList.filter((item) => {
            return !rowIndexs.includes(item.id)
          })
          this.handleCount()
        })
      },
      handlePurchase() {
        if (!this.params.supplierId) {
          this.$confirm('请先选择供应商', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          }).then(() => {})
          return
        }
        this.$refs.purchaseOrderDialog.show()
      },
      // 确定来源订单
      confirmSubmit(arr) {
        const ids = this.params.billDetailList.map((el) => {
          return el.id
        })
        arr.forEach((item) => {
          if (!ids.includes(item.id)) {
            this.params.billDetailList.push({
              ...item,
              noteDetailId: item.id
            })
          }
        })
        this.handleCount()
      },
      // 计算
      handleCount() {
        //   实际收货数量 receivedQuantity
        //   unitPrice:'单价(含税)',
        // untaxedPrice:'单价(不含税)',
        this.params.totalAccount = ''
        let totalAmount = 0
        let untaxedPrice = 0
        let totalAccount = 0
        this.params.billDetailList?.forEach((item) => {
          totalAccount += Number(item.receivedQuantity || 0)
          totalAmount += Number(item.unitPrice || 0) * Number(item.receivedQuantity || 0)
          untaxedPrice += Number(item.untaxedPrice || 0) * Number(item.receivedQuantity || 0)
        })
        //   总金额含税
        this.params.totalAmount = totalAmount
        // 总金额(不含税)
        this.params.untaxedAmount = untaxedPrice || 1
        // 总数量
        this.params.totalAccount = totalAccount
      },
      handleBack() {
        this.handleCancel()
      },
      handleCancel() {
        this.$router.go(-1)
        this.closePages()
      },
      getParams(action) {
        return {
          ...this.params,
          beginDate: `${this.params.beginDate} 23:59:59`,
          endDate: `${this.params.endDate} 23:59:59`,
          action
        }
      },
      handleSubmit: throttle(function (action) {
        if (this.params.billDetailList.length == 0) {
          this.$message.error('请至少选择一条收货单')
          return
        }
        this.$refs.params.validate(async (valid) => {
          if (valid) {
            const param = this.getParams(action)
            try {
              this.loading = true
              const { code } = this.params.id ? await apiBillUpdate(param) : await apiBillAdd(param)
              if (code === EnumApiCode.Success) {
                this.$message.success(param.id ? this.$t('common.editSuccess') : this.$t('common.newSuccess'))
                this.handleCancel()
              }
            } finally {
              this.loading = false
            }
          } else {
            return false
          }
        })
      }, 1000)
    }
  }
</script>
<style lang="scss" scoped>
  .rectify-inform-add {
    overflow: auto;
    .statement-inline {
      width: 100%;
      height: calc(100% - 71px);
      padding: 20px;
      overflow-y: auto;
      box-sizing: border-box;
    }
    .panl-title {
      height: 45px;
      // margin: 0 16px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #ededed;
      margin-bottom: 16px;
      span {
        display: inline-block;
        height: 22px;
        line-height: 22px;
        color: #171c26;
        border-left: 2px solid #4474f6;
        padding-left: 12px;
        font-size: 16px;
        font-weight: 700;
      }
    }
    .btnStyle {
      margin-bottom: 16px;
    }
  }
</style>
